<template>
  <div class="register-container">
    <div class="brand-container">
      <div class="logo-container">
        <i class="el-icon chat-icon"><MessageBox /></i>
      </div>
      <h1 class="brand-title">TalkFlow</h1>
      <p class="brand-subtitle">畅享高效沟通，连接美好世界</p>
    </div>
    <div class="register-box">
      <h2>用户注册</h2>
      <div class="register-form">
        <el-form ref="registerFormRef" :model="registerForm" :rules="rules">
          <el-form-item prop="email">
            <el-input 
              v-model="registerForm.email" 
              placeholder="请输入邮箱"
              :prefix-icon="Message"
            />
          </el-form-item>
          <el-form-item prop="code">
            <div class="code-input">
              <el-input 
                v-model="registerForm.code" 
                placeholder="请输入验证码"
                :prefix-icon="Key"
              />
              <el-button 
                type="primary" 
                :disabled="countdown > 0"
                @click="sendVerificationCode"
              >
                {{ countdown > 0 ? `${countdown}s后重试` : '发送验证码' }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item prop="password">
            <el-input 
              v-model="registerForm.password" 
              type="password" 
              placeholder="请输入密码"
              :prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input 
              v-model="registerForm.confirmPassword" 
              type="password" 
              placeholder="请确认密码"
              :prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button 
              type="primary" 
              class="register-btn" 
              :loading="loading"
              @click="handleRegister"
            >
              注册
            </el-button>
          </el-form-item>
          <div class="login-link">
            已有账号？<router-link to="/login">立即登录</router-link>
          </div>
        </el-form>
      </div>
    </div>
    <div class="footer">
      <p>© 2023 TalkFlow 聊天应用 - 连接沟通，畅享交流</p>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Lock, Message, Key, MessageBox } from '@element-plus/icons-vue'
import { register, sendEmailCode } from '@/api/user'

export default {
  name: 'RegisterPage',
  setup() {
    const router = useRouter()
    const registerFormRef = ref(null)
    const loading = ref(false)
    const countdown = ref(0)

    const registerForm = reactive({
      email: '',
      code: '',
      password: '',
      confirmPassword: ''
    })

    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (registerForm.confirmPassword !== '') {
          setTimeout(() => {
            registerFormRef.value.validateField('confirmPassword')
          }, 0)
        }
        callback()
      }
    }

    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    const rules = {
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { validator: validatePass, trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        { validator: validatePass2, trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
      ]
    }

    const startCountdown = () => {
      countdown.value = 60
      const timer = setInterval(() => {
        if (countdown.value > 0) {
          countdown.value--
        } else {
          clearInterval(timer)
        }
      }, 1000)
    }

    const sendVerificationCode = async () => {
      try {
        await registerFormRef.value.validateField('email')
        await sendEmailCode(registerForm.email)
        ElMessage.success('验证码已发送')
        startCountdown()
      } catch (error) {
        console.error('发送验证码失败：', error)
      }
    }

    const handleRegister = async () => {
      if (!registerFormRef.value) return
      
      try {
        // 先检查确认密码是否一致
        if (registerForm.password !== registerForm.confirmPassword) {
          ElMessage.error('两次输入密码不一致')
          return
        }
        
        await registerFormRef.value.validate()
        loading.value = true
        
        // 剔除确认密码字段
        const registerData = {
          email: registerForm.email,
          code: registerForm.code,
          password: registerForm.password
        }
        
        const res = await register(registerData)
        ElMessage.success('注册成功，已生成您的TF ID：' + res.tfId)
        
        // 跳转到登录页面
        setTimeout(() => {
          router.push('/login')
        }, 1500)
      } catch (error) {
        console.error('注册失败：', error)
      } finally {
        loading.value = false
      }
    }

    return {
      registerFormRef,
      loading,
      countdown,
      registerForm,
      rules,
      Lock,
      Message,
      Key,
      MessageBox,
      sendVerificationCode,
      handleRegister
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  padding: 20px;
}

.brand-container {
  text-align: center;
  margin-bottom: 30px;
  color: white;
}

.logo-container {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 80px;
  background-color: white;
  border-radius: 50%;
  margin-bottom: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.chat-icon {
  font-size: 40px;
  color: #764ba2;
}

.brand-title {
  font-size: 42px;
  font-weight: bold;
  margin: 0 0 10px;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.brand-subtitle {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
}

.register-box {
  width: 420px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-weight: 500;
}

.code-input {
  display: flex;
  gap: 10px;
}

.code-input :deep(.el-input) {
  flex: 1;
}

.register-btn {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
  background: linear-gradient(to right, #667eea, #764ba2);
  border: none;
  transition: transform 0.3s;
}

.register-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(118, 75, 162, 0.3);
}

.login-link {
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
  color: #666;
}

.login-link a {
  color: #764ba2;
  text-decoration: none;
  font-weight: 500;
}

.login-link a:hover {
  text-decoration: underline;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  padding: 6px 11px;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #764ba2 inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #764ba2 inset !important;
}

:deep(.el-button--primary) {
  --el-button-bg-color: #764ba2;
  --el-button-border-color: #764ba2;
  --el-button-hover-bg-color: #8a63b1;
  --el-button-hover-border-color: #8a63b1;
  --el-button-active-bg-color: #673d91;
}

.footer {
  position: absolute;
  bottom: 20px;
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
}
</style> 